<template>
	<el-main style="padding: 0px">
		<div class="planView-container" v-loading="state.exportLoading">
			<!-- 快捷配置 -->
			<!-- <QuickConfig :available-areas="state.dropdownData.workAreaId" :available-categories="state.dropdownData.className" :query-params="state.queryParams" /> -->

			<!-- 计划筛选内容 -->
			<QueryForm :dropdown-data="state.dropdownData" :initial-query-params="state.queryParams" @query="handleQuery" @reset="handleReset" />

			<!-- 统计卡片 -->
			<StatisticsCards :statistics-data="store.statisticsCardsData" :loading="store.loadingStates.statisticsCards" :error="false" @retry="handleRetry" />

			<!-- 综合分析 - 使用tabs组件整合所有分析内容 -->
			<el-card class="plan-analysis-tabs art-custom-card" shadow="hover">
				<template #header>
					<div class="card-header">
						<el-icon style="display: inline; vertical-align: middle"> <ele-DataAnalysis /> </el-icon>
						<span>综合分析</span>
						<div class="header-actions">
							<el-button type="danger" size="small" :icon="Bell" :loading="state.notificationLoading" @click="handleSendNotifications" title="推送延期通知" style="cursor: pointer" :disabled="false" v-auth="'planview:sendNotification'">
								推送通知
							</el-button>
							<el-button type="warning" size="small" :icon="Delete" @click="handleClearCache" title="清除缓存"> 清除缓存 </el-button>
							<el-button type="primary" size="small" :icon="Refresh" :loading="state.refreshLoading" @click="handleRefresh" title="刷新数据"> 刷新 </el-button>
						</div>
					</div>
				</template>
				<el-tabs v-model="activeTab" type="card" class="analysis-tabs" @tab-click="handleTabClick">
					<!-- 月度看板 -->
					<el-tab-pane label="月度看板" name="monthly" lazy>
						<template #label>
							<el-icon style="margin-right: 4px"><ele-TrendCharts /></el-icon>
							月度看板
						</template>
						<div data-tab="monthly" class="monthly-tab-content" v-loading="store.loadingStates.monthlyChart">
							<!-- 显示模式选择 -->
							<div class="monthly-display-mode-selector">
								<el-radio-group v-model="monthlyDisplayMode" size="small">
									<el-radio-button value="split">分离显示</el-radio-button>
									<el-radio-button value="combined">合并显示</el-radio-button>
								</el-radio-group>
							</div>
							
							<!-- 分离显示模式 -->
							<div v-if="monthlyDisplayMode === 'split'" class="monthly-split-mode">
								<div class="monthly-chart-item">
									<CombinedAreaChart 
										:chart-data="store.monthlyData" 
										:area-name="'开工情况'"
										:show-time-progress="false"
										:show-split-layout="false"
										:chart-type="'start'"
										ref="monthlyStartChartComponent"
									/>
								</div>
								<div class="monthly-chart-item">
									<CombinedAreaChart 
										:chart-data="store.monthlyData" 
										:area-name="'完工情况'"
										:show-time-progress="false"
										:show-split-layout="false"
										:chart-type="'end'"
										ref="monthlyEndChartComponent"
									/>
								</div>
							</div>
							
							<!-- 合并显示模式 -->
							<div v-else class="monthly-combined-mode">
								<CombinedAreaChart 
									:chart-data="store.monthlyData" 
									:area-name="'总体情况'"
									:show-time-progress="true"
									:show-split-layout="false"
									ref="monthlyChartComponent"
								/>
							</div>
						</div>
					</el-tab-pane>

					<!-- 各区域完工情况 -->
					<el-tab-pane label="各区域完工情况" name="areas" v-if="filteredAreas.length > 0" lazy>
						<template #label>
							<el-icon style="margin-right: 4px"><ele-Location /></el-icon>
							各区域完工情况
							<span class="filter-info" v-if="state.queryParams.className"> (筛选分类: {{ getClassNameLabel(state.queryParams.className) }}) </span>
						</template>
						<div data-tab="areas" v-loading="store.loadingStates.areas">
							<AreaChartsContainer
								ref="areaChartsRef"
								v-if="Object.keys(areaDataCache).length > 0"
								:areas="filteredAreas"
								:query-params="state.queryParams"
                            :chart-data-cache="areaDataCache"
                            :key="`area-${activeTab}-${(state.queryParams as any).rangeStart}-${(state.queryParams as any).rangeEnd}-${state.queryParams.className}-${state.queryParams.workAreaId}`"
							/>
							<div v-else-if="!store.loadingStates.areas" class="empty-placeholder">
								<el-empty description="暂无区域数据" />
							</div>
						</div>
					</el-tab-pane>

					<!-- 各分类完工情况 -->
					<el-tab-pane label="各分类完工情况" name="categories" v-if="filteredCategories.length > 0" lazy>
						<template #label>
							<el-icon style="margin-right: 4px"><ele-Files /></el-icon>
							各分类完工情况
							<span class="filter-info" v-if="state.queryParams.workAreaId"> (筛选区域: {{ getWorkAreaLabel(state.queryParams.workAreaId) }}) </span>
						</template>
						<div data-tab="categories" v-loading="store.loadingStates.categories">
							<CategoryChartsContainer
								ref="categoryChartsRef"
								v-if="Object.keys(categoryDataCache).length > 0"
								:categories="filteredCategories"
								:query-params="state.queryParams"
                            :chart-data-cache="categoryDataCache"
                            :key="`category-${activeTab}-${(state.queryParams as any).rangeStart}-${(state.queryParams as any).rangeEnd}-${state.queryParams.className}-${state.queryParams.workAreaId}`"
							/>
							<div v-else-if="!store.loadingStates.categories" class="empty-placeholder">
								<el-empty description="暂无分类数据" />
							</div>
						</div>
					</el-tab-pane>

					<!-- 延期情况分析 -->
					<el-tab-pane label="延期情况分析" name="delay" lazy>
						<template #label>
							<el-icon style="margin-right: 4px"><ele-Warning /></el-icon>
							延期情况分析
						</template>
						<div data-tab="delay" class="delay-tab-content">
							<div class="analysis-charts">
								<!-- 区域延期情况总览 -->
								<div class="chart-section">
									<div class="section-header">
										<el-icon><ele-Location /></el-icon>
										<span>各区域延期情况</span>
										<span class="filter-info" v-if="state.queryParams.className"> (筛选分类: {{ getClassNameLabel(state.queryParams.className) }}) </span>
									</div>
									<div class="chart-container">
										<div ref="areaDelayChartRef" style="width: 100%; height: 100%; min-height: 400px" v-loading="state.exportLoading"></div>
									</div>
								</div>

								<!-- 分类延期情况总览 -->
								<div class="chart-section">
									<div class="section-header">
										<el-icon><ele-Files /></el-icon>
										<span>各分类延期情况</span>
										<span class="filter-info" v-if="state.queryParams.workAreaId"> (筛选区域: {{ getWorkAreaLabel(state.queryParams.workAreaId) }}) </span>
									</div>
									<div class="chart-container">
										<div ref="categoryDelayChartRef" style="width: 100%; height: 100%; min-height: 400px" v-loading="state.exportLoading"></div>
									</div>
								</div>
							</div>
						</div>
					</el-tab-pane>

					<!-- 延期明细列表 -->
					<el-tab-pane label="延期明细列表" name="delayDetails" lazy>
						<template #label>
							<el-icon style="margin-right: 4px"><ele-Document /></el-icon>
							延期明细列表
						</template>
						<div data-tab="delayDetails" class="delay-details-tab-content">
							<DelayDetailTables :filter-params="state.queryParams" />
						</div>
					</el-tab-pane>

					<!-- 计划清单 -->
					<el-tab-pane label="计划清单" name="lists" lazy>
						<template #label>
							<el-icon style="margin-right: 4px"><ele-List /></el-icon>
							计划清单
						</template>
						<div data-tab="lists" class="plan-lists-tab-content">
							<PlanListsContainer :query-params="state.queryParams" />
						</div>
					</el-tab-pane>

					<!-- 周期分析（树形/透视） -->
					<el-tab-pane label="周期分析" name="cycles" lazy>
						<template #label>
							<el-icon style="margin-right: 4px"><ele-DataLine /></el-icon>
							周期分析
						</template>
						<div data-tab="cycles" class="cycle-analysis-tab-content">
							<CycleAnalysisContainer :query-params="state.queryParams" />
						</div>
					</el-tab-pane>

					<!-- 更新信息分析 -->
					<el-tab-pane label="更新信息分析" name="updateAnalysis" lazy>
						<template #label>
							<el-icon style="margin-right: 4px"><ele-Refresh /></el-icon>
							更新信息分析
						</template>
						<div data-tab="updateAnalysis" class="update-analysis-tab-content">
							<UpdateAnalysisTable :filter-params="state.queryParams" />
						</div>
					</el-tab-pane>
				</el-tabs>
			</el-card>
		</div>

		<!-- 通知配置对话框 -->
		<NotificationConfigDialog
			v-model:visible="state.notificationConfigDialog.visible"
			v-model:formData="state.notificationConfigDialog.formData"
			:preview="state.notificationConfigDialog.preview"
			:loading="state.notificationConfigDialog.loading"
			:previewLoading="state.notificationConfigDialog.previewLoading"
			:userOptions="state.notificationConfigDialog.userOptions"
			:roleOptions="state.notificationConfigDialog.roleOptions"
			:classNameOptions="state.dropdownData.className"
			:workAreaOptions="state.dropdownData.workAreaId"
			@preview="handlePreviewRecipients"
			@confirm="handleConfirmSendNotification"
		/>
	</el-main>
</template>

<script lang="ts" setup name="planView">
import { ref, reactive, onMounted, computed, nextTick, watch, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Refresh } from '@element-plus/icons-vue';
import { usePlanViewApi } from '/@/api/plans/planView';
import { usePlanDelayViewApi, type PlanDelayStartInput, type PlanDelayAllInput } from '/@/api/plans/planDelayView';
import { usePlanTypeApi } from '/@/api/plans/planType';
import { getAPI } from '/@/utils/axios-utils';
import { SysOrgApi, SysUserApi, SysRoleApi } from '/@/api-services/api';
import { SysOrg } from '/@/api-services/models';
import { QueryForm, StatisticsCards, StartChart, EndChart, AreaChartsContainer, CategoryChartsContainer, QuickConfig, CombinedAreaChart, UpdateAnalysisTable, PlanListsContainer, CycleAnalysisContainer } from './components';
import { DelayDetailTables } from '../plandelayview/components';
import NotificationConfigDialog from './components/NotificationConfigDialog.vue';
import * as echarts from 'echarts';
import { signalR } from '/@/views/system/onlineUser/signalR';
import { ElMessageBox, ElNotification } from 'element-plus';
import { Bell, Delete } from '@element-plus/icons-vue';
import { auth } from '/@/utils/authFunction';
import { usePlanViewStore } from '/@/stores/planViewStore';

// 使用Pinia Store管理状态
const store = usePlanViewStore();

const activeTab = ref('monthly'); // 默认选中月度看板tab
const monthlyDisplayMode = ref<'split' | 'combined'>('split'); // 月度看板显示模式

// ECharts DOM引用 - 延期图表
const areaDelayChartRef = ref<HTMLElement>();
const categoryDelayChartRef = ref<HTMLElement>();

// ECharts实例 - 延期图表
let areaDelayChartInstance: echarts.ECharts | null = null;
let categoryDelayChartInstance: echarts.ECharts | null = null;

const planViewApi = usePlanViewApi();
const planDelayViewApi = usePlanDelayViewApi();
const planTypeApi = usePlanTypeApi();
const sysUserApi = getAPI(SysUserApi);
const sysRoleApi = getAPI(SysRoleApi);

// 防抖函数
const debounce = (func: Function, wait: number) => {
	let timeout: NodeJS.Timeout;
	return function executedFunction(...args: any[]) {
		const later = () => {
			clearTimeout(timeout);
			func(...args);
		};
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
	};
};


// 精简的本地状态 - 主要数据已移至Pinia Store
const state = reactive({
	refreshLoading: false,
	notificationLoading: false, // 通知推送加载状态
	autoRefresh: false, // 自动刷新开关
	autoRefreshInterval: 300000, // 自动刷新间隔（5分钟）
	dropdownData: {
		className: [] as Array<{ value: number | null; label: string }>,
		workAreaId: [] as Array<{ value: number | null; label: string }>,
	},
	queryParams: {
		workTime: (() => {
			const now = new Date();
			const day = now.getDate();
			
			if (day >= 26) {
				// 当前日期是26号或之后，业务月是下个月
				const nextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
				return `${nextMonth.getFullYear()}-${String(nextMonth.getMonth() + 1).padStart(2, '0')}`;
			} else {
				// 当前日期是25号或之前，业务月是当前月
				return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
			}
		})(),
		className: null as number | null,
		workAreaId: null as number | null,
		keyword: '',
		advancedField: '',
		planStart: false, // 默认未完成 - 延期查询用
	},
	// 延期图表数据缓存（这部分暂时保留，后续可移至Store）
	// 移除：延期图表数据缓存已迁移到Store管理
	// areaDelayChartDataCache: null as any,
	// categoryDelayChartDataCache: null as any,
	// 通知配置对话框
	notificationConfigDialog: {
		visible: false,
		loading: false,
		previewLoading: false,
		formData: {
			workTime: '',
			className: undefined as number | undefined,
			workAreaId: undefined as number | undefined,
			notificationType: 3,
			delayLevels: [4],
			recipientMode: 1,
			specificUserIds: [] as number[],
			specificRoleIds: [] as number[],
			includeSubordinates: false,
			customMessage: '',
		},
		preview: null as any, // 接收人预览数据
		userOptions: [] as Array<{ value: number; label: string; phone?: string; email?: string }>,
		roleOptions: [] as Array<{ value: number; label: string; code?: string }>,
	},
});

const areaChartsRef = ref();
const categoryChartsRef = ref();
const monthlyChartComponent = ref();
const monthlyStartChartComponent = ref();
const monthlyEndChartComponent = ref();

// 记录已加载的tab
const loadedTabs = ref(new Set<string>());

// 自动刷新定时器
let autoRefreshTimer: NodeJS.Timeout | null = null;

// 计算属性：转换Store数据为组件所需格式
const areaDataCache = computed(() => {
	if (!store.areaData) return {};
	const cache: Record<number, any[]> = {};
	store.areaData.forEach(area => {
		if (area.areaId) {
			cache[area.areaId] = area.chartData || [];
		}
	});
	return cache;
});

const categoryDataCache = computed(() => {
	console.log('[DEBUG] 计算categoryDataCache:', { 
		hasCategoryData: !!store.categoryData, 
		categoryDataLength: store.categoryData?.length || 0,
		categoryData: store.categoryData
	});
	
	if (!store.categoryData) return {};
	const cache: Record<number, any[]> = {};
	store.categoryData.forEach(category => {
		if (category.categoryId) {
			// 使用分类ID作为key，与filteredCategories的category.value匹配
			cache[category.categoryId] = category.chartData || [];
			console.log('[DEBUG] 添加分类到缓存:', {
				categoryId: category.categoryId,
				categoryName: category.categoryName,
				chartDataLength: category.chartData?.length || 0
			});
		}
	});
	
	console.log('[DEBUG] 最终categoryDataCache:', cache);
	return cache;
});


// 检查DOM元素是否准备好
const isDOMReady = (selector: string): boolean => {
	const element = document.querySelector(selector) as HTMLElement;
	if (!element) return false;
	const style = window.getComputedStyle(element);
	return element.offsetWidth > 0 && element.offsetHeight > 0 && style.display !== 'none' && style.visibility !== 'hidden';
};

// 等待DOM元素准备好
const waitForDOMReady = (selector: string, maxWait = 2000): Promise<boolean> => {
	return new Promise((resolve) => {
		const startTime = Date.now();

		const check = () => {
			if (isDOMReady(selector)) {
				resolve(true);
				return;
			}

			if (Date.now() - startTime > maxWait) {
				console.warn(`DOM element ${selector} not ready after ${maxWait}ms`);
				resolve(false);
				return;
			}

			setTimeout(check, 50);
		};

		check();
	});
};

// Tab懒加载处理函数
async function handleTabClick(tab: any) {
	let tabName = '';
	// 兼容 tab 可能为字符串或对象
	if (typeof tab === 'string') {
		tabName = tab;
	} else if (tab && typeof tab.name === 'string') {
		tabName = tab.name;
	} else if (tab && typeof tab.paneName === 'string') {
		tabName = tab.paneName;
	} else {
		console.warn('Tab name is undefined or null', tab);
		return;
	}

	// 懒加载：仅在需要时加载对应Tab的数据
	try {
    const queryParams = {
        workTime: state.queryParams.workTime,
        className: state.queryParams.className,
        workAreaId: state.queryParams.workAreaId,
        rangeStart: (state.queryParams as any).rangeStart,
        rangeEnd: (state.queryParams as any).rangeEnd,
        periodType: (state.queryParams as any).periodType,
        year: (state.queryParams as any).year,
        quarter: (state.queryParams as any).quarter,
    } as any;

		switch (tabName) {
			case 'monthly':
				// 月度看板数据在初次加载时已经获取
				break;
			case 'areas':
				if (!store.isTabLoaded('areas')) {
					// 获取要显示的区域ID列表
					const areaIds = filteredAreas.value
						.filter(area => area.value !== null)
						.map(area => area.value as number);
					await store.loadAreaData(queryParams, areaIds);
				}
				break;
			case 'categories':
				if (!store.isTabLoaded('categories')) {
					// 获取要显示的分类ID列表
					const categoryIds = filteredCategories.value
						.filter(category => category.value !== null)
						.map(category => category.value as number);
					await store.loadCategoryData(queryParams, categoryIds);
				}
				break;
			case 'delay':
				if (!store.isTabLoaded('delay')) {
					await store.loadDelayAnalysisData(queryParams);
				}
				break;
			case 'delayDetails':
				// 延期详情需要额外处理
				await fetchDelayDetailsData();
				break;
			case 'lists':
				// 计划清单不需要特殊加载，组件内部自行处理
				break;
			case 'updateAnalysis':
				// 更新分析数据
				await fetchUpdateAnalysisData();
				break;
		}
	} catch (error) {
		console.error(`加载${tabName}数据失败:`, error);
		ElMessage.error(`加载${tabName}数据失败`);
	}

	// 标记当前tab为已加载
	loadedTabs.value.add(tabName);

	// 图表resize处理
	nextTick(async () => {
		// 等待DOM元素准备好
		const selector = `[data-tab="${tabName}"]`;
		const isReady = await waitForDOMReady(selector);

		if (isReady) {
			// DOM元素已准备好，执行resize
			if (tabName === 'monthly') {
				if (monthlyDisplayMode.value === 'combined' && monthlyChartComponent.value?.resize) {
					monthlyChartComponent.value.resize();
					setTimeout(() => monthlyChartComponent.value?.resize(), 200);
					setTimeout(() => monthlyChartComponent.value?.resize(), 500);
				} else if (monthlyDisplayMode.value === 'split') {
					if (monthlyStartChartComponent.value?.resize) {
						monthlyStartChartComponent.value.resize();
						setTimeout(() => monthlyStartChartComponent.value?.resize(), 200);
						setTimeout(() => monthlyStartChartComponent.value?.resize(), 500);
					}
					if (monthlyEndChartComponent.value?.resize) {
						monthlyEndChartComponent.value.resize();
						setTimeout(() => monthlyEndChartComponent.value?.resize(), 200);
						setTimeout(() => monthlyEndChartComponent.value?.resize(), 500);
					}
				}
			}
			if (tabName === 'areas' && areaChartsRef.value?.resize) {
				areaChartsRef.value.resize();
				setTimeout(() => areaChartsRef.value?.resize(), 200);
				setTimeout(() => areaChartsRef.value?.resize(), 500);
			}
			if (tabName === 'categories' && categoryChartsRef.value?.resize) {
				categoryChartsRef.value.resize();
				setTimeout(() => categoryChartsRef.value?.resize(), 200);
				setTimeout(() => categoryChartsRef.value?.resize(), 500);
			}
			// 处理延期图表resize
			if (tabName === 'delay') {
				// 延期图表需要在切换到该tab时重新加载数据和初始化
				setTimeout(async () => {
					try {
						// 延期数据现在由Store管理，无需重新获取
						// await fetchDelayData(); // 已移除，使用Store数据

						// 延迟初始化图表，确保DOM已渲染且数据已加载
						setTimeout(() => {
							initDelayCharts();

							// 再次延迟渲染，确保图表实例已创建
							setTimeout(() => {
								renderAreaDelayChart();
								renderCategoryDelayChart();

								// 最后执行resize
								if (areaDelayChartInstance) {
									areaDelayChartInstance.resize();
									setTimeout(() => areaDelayChartInstance && areaDelayChartInstance.resize(), 200);
									setTimeout(() => areaDelayChartInstance && areaDelayChartInstance.resize(), 500);
								}
								if (categoryDelayChartInstance) {
									categoryDelayChartInstance.resize();
									setTimeout(() => categoryDelayChartInstance && categoryDelayChartInstance.resize(), 200);
									setTimeout(() => categoryDelayChartInstance && categoryDelayChartInstance.resize(), 500);
								}
							}, 150);
						}, 100);
					} catch (error) {
						console.error('延期图表初始化失败:', error);
					}
				}, 50);
			}
		} else {
			// 如果DOM元素未准备好，延迟重试
			setTimeout(() => {
				if (tabName === 'monthly') {
					if (monthlyDisplayMode.value === 'combined' && monthlyChartComponent.value?.resize) {
						monthlyChartComponent.value.resize();
						setTimeout(() => monthlyChartComponent.value?.resize(), 200);
						setTimeout(() => monthlyChartComponent.value?.resize(), 500);
					} else if (monthlyDisplayMode.value === 'split') {
						if (monthlyStartChartComponent.value?.resize) {
							monthlyStartChartComponent.value.resize();
							setTimeout(() => monthlyStartChartComponent.value?.resize(), 200);
							setTimeout(() => monthlyStartChartComponent.value?.resize(), 500);
						}
						if (monthlyEndChartComponent.value?.resize) {
							monthlyEndChartComponent.value.resize();
							setTimeout(() => monthlyEndChartComponent.value?.resize(), 200);
							setTimeout(() => monthlyEndChartComponent.value?.resize(), 500);
						}
					}
				}
				if (tabName === 'areas' && areaChartsRef.value?.resize) {
					areaChartsRef.value.resize();
					setTimeout(() => areaChartsRef.value?.resize(), 200);
					setTimeout(() => areaChartsRef.value?.resize(), 500);
				}
				if (tabName === 'categories' && categoryChartsRef.value?.resize) {
					categoryChartsRef.value.resize();
					setTimeout(() => categoryChartsRef.value?.resize(), 200);
					setTimeout(() => categoryChartsRef.value?.resize(), 500);
				}
				if (tabName === 'delay') {
					// 延期图表需要在切换到该tab时重新加载数据和初始化
					setTimeout(async () => {
						try {
							// 延期数据现在由Store管理，无需重新获取
							// await fetchDelayData(); // 已移除，使用Store数据

							// 延迟初始化图表，确保DOM已渲染且数据已加载
							setTimeout(() => {
								initDelayCharts();

								// 再次延迟渲染，确保图表实例已创建
								setTimeout(() => {
									renderAreaDelayChart();
									renderCategoryDelayChart();

									// 最后执行resize
									if (areaDelayChartInstance) {
										areaDelayChartInstance.resize();
										setTimeout(() => areaDelayChartInstance && areaDelayChartInstance.resize(), 200);
										setTimeout(() => areaDelayChartInstance && areaDelayChartInstance.resize(), 500);
									}
									if (categoryDelayChartInstance) {
										categoryDelayChartInstance.resize();
										setTimeout(() => categoryDelayChartInstance && categoryDelayChartInstance.resize(), 200);
										setTimeout(() => categoryDelayChartInstance && categoryDelayChartInstance.resize(), 500);
									}
								}, 150);
							}, 100);
						} catch (error) {
							console.error('延期图表初始化失败:', error);
						}
					}, 50);
				}
			}, 500);
		}
	});
}

// 根据筛选条件过滤区域数据 - 修复逻辑
const filteredAreas = computed(() => {
	// 如果选择了特定区域，只显示该区域
	if (state.queryParams.workAreaId) {
		return state.dropdownData.workAreaId.filter((area) => area.value === state.queryParams.workAreaId);
	}
	// 如果没有选择区域，显示所有区域
	return state.dropdownData.workAreaId;
});

// 根据筛选条件过滤分类数据 - 修复逻辑
const filteredCategories = computed(() => {
	// 如果选择了特定分类，只显示该分类
	if (state.queryParams.className) {
		return state.dropdownData.className.filter((category) => category.value === state.queryParams.className);
	}
	// 如果没有选择分类，显示所有分类
	return state.dropdownData.className;
});

// 自动选择默认tab
const autoSelectTab = () => {
	// 默认选中月度看板，如果当前没有选中任何tab
	if (!activeTab.value || !['monthly', 'areas', 'categories', 'delay', 'delayDetails', 'lists', 'updateAnalysis'].includes(activeTab.value)) {
		activeTab.value = 'monthly';
	}

	// 标记默认选中的tab为已加载
	if (activeTab.value) {
		loadedTabs.value.add(activeTab.value);
	}
};

// 获取分类名称
const getClassNameLabel = (classNameId: number | null) => {
	if (!classNameId) return '';
	const category = state.dropdownData.className.find((c) => c.value === classNameId);
	return category?.label || '';
};

// 获取区域名称
const getWorkAreaLabel = (workAreaId: number | null) => {
	if (!workAreaId) return '';
	const area = state.dropdownData.workAreaId.find((a) => a.value === workAreaId);
	return area?.label || '';
};

// 加载下拉数据
const loadDropdownData = async () => {
	// 分类
	const planTypeData = await planTypeApi.page({ page: 1, pageSize: 99999999 }).then((res) => res.data.result);
	// 确保按后端的 OrderNo 排序（后端已排序，这里再兜底一次）
	state.dropdownData.className = (planTypeData?.items ?? [])
		.sort((a: any, b: any) => (a.orderNo ?? 0) - (b.orderNo ?? 0))
		.map((item: any) => ({ value: item.id, label: item.name }));
	// 区域 - 获取所有组织并过滤出作业区
	const orgData = await getAPI(SysOrgApi)
		.apiSysOrgListGet(0)
		.then((res) => res.data.result);
	
	// 递归提取所有组织，然后过滤出作业区
	const extractAllOrgs = (orgs: SysOrg[]): SysOrg[] => {
		const result: SysOrg[] = [];
		orgs.forEach((org) => {
			result.push(org);
			if (org.children && org.children.length > 0) {
				result.push(...extractAllOrgs(org.children));
			}
		});
		return result;
	};
	
	// 过滤出名称包含"作业区"的组织
	const extractWorkAreas = (orgs: SysOrg[]): Array<{ value: number | null; label: string; orderNo?: number }> => {
		return orgs
			.filter(org => org.name && org.name.includes('作业区'))
			.map(org => ({
				value: org.id ?? null,
				label: org.name || '',
				orderNo: (org as any).orderNo ?? 0,
			}))
			.sort((a, b) => (a.orderNo ?? 0) - (b.orderNo ?? 0));
	};
	
	const allOrgs = extractAllOrgs(orgData || []);
	const workAreas = extractWorkAreas(allOrgs);
	// 去除中间的排序字段，仅保留 value/label
	state.dropdownData.workAreaId = workAreas.map(w => ({ value: w.value, label: w.label }));
};

// 使用超级优化接口 - 性能优化版本，减少数据转换操作
// 已移除fetchSuperOptimizedData函数，现在使用Pinia Store中的方法

// 监听查询参数变化，重置已加载的tab状态
watch(
    () => [
        (state.queryParams as any).rangeStart,
        (state.queryParams as any).rangeEnd,
        state.queryParams.className,
        state.queryParams.workAreaId,
        state.queryParams.keyword
    ],
    () => {
        // 清空已加载的tab记录，强制重新加载
        loadedTabs.value.clear();
    },
    { deep: true }
);

onMounted(async () => {
	await loadDropdownData();
	const now = new Date();
	const day = now.getDate();
	
	if (day >= 26) {
		// 当前日期是26号或之后，业务月是下个月
		const nextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
		state.queryParams.workTime = `${nextMonth.getFullYear()}-${String(nextMonth.getMonth() + 1).padStart(2, '0')}`;
	} else {
		// 当前日期是25号或之前，业务月是当前月
		state.queryParams.workTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
	}

	// 使用新的Store方法加载基础数据
    const queryParams = {
        workTime: state.queryParams.workTime,
        className: state.queryParams.className,
        workAreaId: state.queryParams.workAreaId,
        rangeStart: (state.queryParams as any).rangeStart,
        rangeEnd: (state.queryParams as any).rangeEnd,
        periodType: (state.queryParams as any).periodType,
        year: (state.queryParams as any).year,
        quarter: (state.queryParams as any).quarter,
    } as any;
	
	await Promise.all([
		store.loadStatisticsCardsData(queryParams),
		store.loadMonthlyChartData(queryParams)
	]);

	// 自动选择默认tab
	autoSelectTab();

	// 初始化SignalR延期通知监听
	initSignalRNotificationListener();

	// 只在有推送通知权限时才初始化通知配置对话框数据
	if (auth('planview:sendNotification')) {
		await initUserOptions();
		await initRoleOptions();
	}

	// 延迟执行resize，确保ECharts正确初始化
	setTimeout(() => {
		if (activeTab.value === 'monthly') {
			if (monthlyDisplayMode.value === 'combined' && monthlyChartComponent.value?.resize) {
				monthlyChartComponent.value.resize();
			} else if (monthlyDisplayMode.value === 'split') {
				if (monthlyStartChartComponent.value?.resize) {
					monthlyStartChartComponent.value.resize();
				}
				if (monthlyEndChartComponent.value?.resize) {
					monthlyEndChartComponent.value.resize();
				}
			}
		}
		if (activeTab.value === 'areas' && areaChartsRef.value?.resize) {
			areaChartsRef.value.resize();
		}
		if (activeTab.value === 'categories' && categoryChartsRef.value?.resize) {
			categoryChartsRef.value.resize();
		}
	}, 1000);
});

// 窗口大小变化时自动resize图表
const handleWindowResize = () => {
	// 使用nextTick和更长的延迟来避免主进程中resize
	nextTick(() => {
		setTimeout(() => {
			if (activeTab.value === 'monthly') {
				if (monthlyDisplayMode.value === 'combined' && monthlyChartComponent.value?.resize) {
					monthlyChartComponent.value.resize();
				} else if (monthlyDisplayMode.value === 'split') {
					if (monthlyStartChartComponent.value?.resize) {
						monthlyStartChartComponent.value.resize();
					}
					if (monthlyEndChartComponent.value?.resize) {
						monthlyEndChartComponent.value.resize();
					}
				}
			}
			if (activeTab.value === 'areas' && areaChartsRef.value?.resize) {
				areaChartsRef.value.resize();
			}
			if (activeTab.value === 'categories' && categoryChartsRef.value?.resize) {
				categoryChartsRef.value.resize();
			}
		}, 200);
	});
};

// 监听窗口大小变化
window.addEventListener('resize', handleWindowResize);

// 启动自动刷新
const startAutoRefresh = () => {
	if (autoRefreshTimer) {
		clearInterval(autoRefreshTimer);
	}

	if (state.autoRefresh) {
		autoRefreshTimer = setInterval(async () => {
			console.log('自动刷新数据...');
			const queryParams = {
				workTime: state.queryParams.workTime,
				className: state.queryParams.className,
				workAreaId: state.queryParams.workAreaId,
			};
			await store.refreshAllData(queryParams);
		}, state.autoRefreshInterval);
	}
};

// 停止自动刷新
const stopAutoRefresh = () => {
	if (autoRefreshTimer) {
		clearInterval(autoRefreshTimer);
		autoRefreshTimer = null;
	}
};

// 切换自动刷新状态
// const toggleAutoRefresh = () => {
// 	state.autoRefresh = !state.autoRefresh;
// 	if (state.autoRefresh) {
// 		startAutoRefresh();
// 		ElMessage.success('已开启自动刷新（5分钟间隔）');
// 	} else {
// 		stopAutoRefresh();
// 		ElMessage.info('已关闭自动刷新');
// 	}
// };

// 监听自动刷新状态变化
watch(
	() => state.autoRefresh,
	(newVal) => {
		if (newVal) {
			startAutoRefresh();
		} else {
			stopAutoRefresh();
		}
	}
);

// 监听Store中的延期分析数据变化，自动渲染图表
watch(
	() => store.delayAnalysisData,
	(newData) => {
		if (newData) {
			nextTick(() => {
				if (newData.areaDelayCharts) {
					renderAreaDelayChart();
				}
				if (newData.categoryDelayCharts) {
					renderCategoryDelayChart();
				}
			});
		}
	},
	{ deep: true }
);

// 组件卸载时移除事件监听器和定时器
onUnmounted(() => {
	window.removeEventListener('resize', handleWindowResize);
	stopAutoRefresh();

	// 销毁延期ECharts实例
	if (areaDelayChartInstance) {
		areaDelayChartInstance.dispose();
		areaDelayChartInstance = null;
	}
	if (categoryDelayChartInstance) {
		categoryDelayChartInstance.dispose();
		categoryDelayChartInstance = null;
	}

	// 移除SignalR延期通知监听
	removeSignalRNotificationListener();
});

const handleQuery = async (params: any) => {
	// 更新查询参数
	Object.assign(state.queryParams, params);

	// 使用新的Store方法加载基础数据
	try {
    const queryParams = {
        workTime: state.queryParams.workTime,
        className: state.queryParams.className,
        workAreaId: state.queryParams.workAreaId,
        rangeStart: (state.queryParams as any).rangeStart,
        rangeEnd: (state.queryParams as any).rangeEnd,
        periodType: (state.queryParams as any).periodType,
        year: (state.queryParams as any).year,
        quarter: (state.queryParams as any).quarter,
    } as any;
		
		// 并行加载基础数据
		await Promise.all([
			store.loadStatisticsCardsData(queryParams),
			store.loadMonthlyChartData(queryParams)
			// fetchDelayDetailsData() // 延期详情数据在Tab懒加载时获取
		]);
		
	} catch (error) {
		console.error('查询数据失败:', error);
		ElMessage.error('查询数据失败');
	}

	// 自动选择默认tab
	autoSelectTab();
};

// 重置查询（清除所有缓存数据）
const handleReset = async () => {
	// 重置查询参数
	state.queryParams = {
		workTime: '',
		className: undefined,
		workAreaId: undefined,
		planStart: false,
	};
	
	// 清除Store中的所有数据
	store.clearAllData();
	
	// 重新加载基础数据
	if (state.queryParams.workTime) {
		await handleQuery(state.queryParams);
	}
};

// 移除：延期统计数据获取已迁移到Store管理
// const fetchDelayData = async () => {
//     // 该函数的功能已经迁移到Store的loadDelayAnalysisData和loadDelayData方法中
//     // 不再需要在组件中维护延期数据的获取逻辑
// };

// 获取延期详情数据
const fetchDelayDetailsData = async () => {
	try {
		// 这里会加载延期详情数据，目前保持原有逻辑
		console.log('加载延期详情数据...');
		// TODO: 实现具体的延期详情数据加载逻辑
	} catch (error) {
		console.error('获取延期详情数据失败:', error);
	}
};

// 获取更新分析数据
const fetchUpdateAnalysisData = async () => {
	try {
    const params = {
        workTime: state.queryParams.workTime,
        className: state.queryParams.className,
        workAreaId: state.queryParams.workAreaId,
        rangeStart: (state.queryParams as any).rangeStart,
        rangeEnd: (state.queryParams as any).rangeEnd,
        periodType: (state.queryParams as any).periodType,
        year: (state.queryParams as any).year,
        quarter: (state.queryParams as any).quarter,
    } as any;
		
		const response = await planViewApi.getUpdateAnalysisData(params);
		if (response?.data?.result) {
			state.updateAnalysisData = response.data.result;
		}
	} catch (error) {
		console.error('获取更新分析数据失败:', error);
	}
};

// 初始化延期ECharts
const initDelayCharts = () => {
	if (areaDelayChartRef.value && !areaDelayChartInstance) {
		areaDelayChartInstance = echarts.init(areaDelayChartRef.value);
	}
	if (categoryDelayChartRef.value && !categoryDelayChartInstance) {
		categoryDelayChartInstance = echarts.init(categoryDelayChartRef.value);
	}
};

// 渲染区域延期图表
const renderAreaDelayChart = () => {
	if (!areaDelayChartInstance && areaDelayChartRef.value) {
		areaDelayChartInstance = echarts.init(areaDelayChartRef.value);
	}

	if (!areaDelayChartInstance) return;
	
	// 使用Store中的延期分析数据
	const delayData = store.delayAnalysisData?.areaDelayCharts;
	if (!delayData) return;

	const data = delayData;
	const option = {
		title: {
			text: '各区域延期情况',
			left: 'center',
			textStyle: { fontSize: 16, fontWeight: 'bold', color: '#303133' },
		},
		tooltip: {
			trigger: 'axis',
			axisPointer: { type: 'shadow' },
			formatter: (params: any) => {
				const dataIndex = params[0].dataIndex;
				return `
					<div style="padding: 8px;">
						<div style="font-weight: bold; margin-bottom: 8px;">${data.categories?.[dataIndex] || ''}</div>
						<div style="color: #409eff;">总计划数: ${data.totalCounts?.[dataIndex] || 0}</div>
						<div style="color: #f56c6c;">延期数量: ${data.delayCounts?.[dataIndex] || 0}</div>
						<div style="color: #e6a23c;">延期率: ${data.delayRates?.[dataIndex] || 0}%</div>
					</div>
				`;
			},
		},
		legend: {
			data: ['总计划数', '延期数量', '延期率'],
			top: 40,
			itemGap: 20,
		},
		grid: { left: '3%', right: '4%', bottom: '8%', top: '20%', containLabel: true },
		xAxis: [
			{
				type: 'category',
				data: data.categories || [],
				axisTick: { alignWithLabel: true },
				axisLabel: { rotate: 0, interval: 0, fontSize: 12 },
			},
		],
		yAxis: [
			{ type: 'value', name: '数量', position: 'left', axisLabel: { formatter: '{value}' } },
			{ type: 'value', name: '延期率(%)', position: 'right', axisLabel: { formatter: '{value}%' } },
		],
		series: [
			{
				name: '总计划数',
				type: 'bar',
				yAxisIndex: 0,
				data: data.totalCounts || [],
				itemStyle: {
					color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
						{ offset: 0, color: '#409eff' },
						{ offset: 1, color: '#79bbff' },
					]),
				},
				barWidth: '25%',
			},
			{
				name: '延期数量',
				type: 'bar',
				yAxisIndex: 0,
				data: data.delayCounts || [],
				itemStyle: {
					color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
						{ offset: 0, color: '#f56c6c' },
						{ offset: 1, color: '#f89898' },
					]),
				},
				barWidth: '25%',
			},
			{
				name: '延期率',
				type: 'line',
				yAxisIndex: 1,
				data: data.delayRates || [],
				lineStyle: { color: '#e6a23c', width: 3 },
				itemStyle: { color: '#e6a23c' },
				symbol: 'circle',
				symbolSize: 8,
				smooth: true,
			},
		],
		animation: true,
		animationDuration: 1000,
		animationEasing: 'cubicOut' as const,
	};

	areaDelayChartInstance.setOption(option, true);
	// 主动触发 window resize，确保 ECharts 能获取到正确宽高
	window.dispatchEvent(new Event('resize'));
	// 新增：延迟resize，确保图表撑满容器
	nextTick(() => {
		setTimeout(() => {
			areaDelayChartInstance && areaDelayChartInstance.resize();
		}, 120);
		setTimeout(() => {
			areaDelayChartInstance && areaDelayChartInstance.resize();
		}, 400);
	});
};

// 渲染分类延期图表
const renderCategoryDelayChart = () => {
	if (!categoryDelayChartInstance && categoryDelayChartRef.value) {
		categoryDelayChartInstance = echarts.init(categoryDelayChartRef.value);
	}

	if (!categoryDelayChartInstance) return;
	
	// 使用Store中的延期分析数据
	const delayData = store.delayAnalysisData?.categoryDelayCharts;
	if (!delayData) return;

	const data = delayData;
	const pieData = (data.categories || []).map((category: string, index: number) => ({
		name: category,
		value: (data.delayCounts || [])[index] || 0,
		total: (data.totalCounts || [])[index] || 0,
		rate: (data.delayRates || [])[index] || 0,
	}));

	const option = {
		title: {
			text: '各分类延期情况',
			left: 'center',
			textStyle: { fontSize: 16, fontWeight: 'bold', color: '#303133' },
		},
		tooltip: {
			trigger: 'item',
			formatter: (params: any) => {
				const data = params.data;
				return `
					<div style="padding: 8px;">
						<div style="font-weight: bold; margin-bottom: 8px;">${data.name}</div>
						<div style="color: #409eff;">总计划数: ${data.total}</div>
						<div style="color: #f56c6c;">延期数量: ${data.value}</div>
						<div style="color: #e6a23c;">延期率: ${data.rate}%</div>
						<div style="color: #909399;">占比: ${params.percent}%</div>
					</div>
				`;
			},
		},
		legend: {
			type: 'scroll',
			orient: 'horizontal',
			bottom: 10,
			data: data.categories || [],
			itemGap: 20,
			textStyle: { fontSize: 12 },
		},
		series: [
			{
				name: '延期分布',
				type: 'pie',
				radius: ['40%', '70%'],
				center: ['50%', '45%'],
				avoidLabelOverlap: false,
				itemStyle: { borderRadius: 8, borderColor: '#fff', borderWidth: 2 },
				label: {
					show: true,
					position: 'outside',
					formatter: (params: any) => `${params.name}\n${params.data.value}项\n${params.percent}%`,
					fontSize: 11,
					fontWeight: 'bold',
				},
				emphasis: {
					label: { show: true, fontSize: 14, fontWeight: 'bold' },
					itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0,0,0,0.5)' },
				},
				labelLine: { show: true, length: 15, length2: 20, smooth: 0.3 },
				data: pieData,
				animationType: 'scale',
				animationDelay: (idx: number) => Math.random() * 200,
				color: [
					new echarts.graphic.LinearGradient(0, 0, 1, 1, [
						{ offset: 0, color: '#667eea' },
						{ offset: 1, color: '#764ba2' },
					]),
					new echarts.graphic.LinearGradient(0, 0, 1, 1, [
						{ offset: 0, color: '#f093fb' },
						{ offset: 1, color: '#f5576c' },
					]),
					new echarts.graphic.LinearGradient(0, 0, 1, 1, [
						{ offset: 0, color: '#4facfe' },
						{ offset: 1, color: '#00f2fe' },
					]),
					new echarts.graphic.LinearGradient(0, 0, 1, 1, [
						{ offset: 0, color: '#43e97b' },
						{ offset: 1, color: '#38f9d7' },
					]),
					new echarts.graphic.LinearGradient(0, 0, 1, 1, [
						{ offset: 0, color: '#fa709a' },
						{ offset: 1, color: '#fee140' },
					]),
					new echarts.graphic.LinearGradient(0, 0, 1, 1, [
						{ offset: 0, color: '#a8edea' },
						{ offset: 1, color: '#fed6e3' },
					]),
				],
			},
		],
	};

	categoryDelayChartInstance.setOption(option, true);
	window.dispatchEvent(new Event('resize'));
	// 新增：延迟resize，确保图表撑满容器
	nextTick(() => {
		setTimeout(() => {
			categoryDelayChartInstance && categoryDelayChartInstance.resize();
		}, 120);
		setTimeout(() => {
			categoryDelayChartInstance && categoryDelayChartInstance.resize();
		}, 400);
	});
};


// 手动刷新数据
const handleRefresh = async () => {
	try {
		state.refreshLoading = true;
		// 清空Store缓存，强制重新获取数据
		store.clearAllData();

		// 使用新的Store方法重新获取数据
		const queryParams = {
			workTime: state.queryParams.workTime,
			className: state.queryParams.className,
			workAreaId: state.queryParams.workAreaId,
		};
		
		await store.refreshAllData(queryParams);

		// 延迟执行resize，确保图表正确渲染
		setTimeout(() => {
			if (activeTab.value === 'monthly') {
				if (monthlyDisplayMode.value === 'combined' && monthlyChartComponent.value?.resize) {
					monthlyChartComponent.value.resize();
				} else if (monthlyDisplayMode.value === 'split') {
					if (monthlyStartChartComponent.value?.resize) {
						monthlyStartChartComponent.value.resize();
					}
					if (monthlyEndChartComponent.value?.resize) {
						monthlyEndChartComponent.value.resize();
					}
				}
			}
			if (activeTab.value === 'areas' && areaChartsRef.value?.resize) {
				areaChartsRef.value.resize();
			}
			if (activeTab.value === 'categories' && categoryChartsRef.value?.resize) {
				categoryChartsRef.value.resize();
			}
			// resize延期图表
			if (areaDelayChartInstance) {
				areaDelayChartInstance.resize();
			}
			if (categoryDelayChartInstance) {
				categoryDelayChartInstance.resize();
			}
		}, 500);

		ElMessage.success('数据刷新成功');
	} catch (error) {
		console.error('刷新数据失败:', error);
		ElMessage.error('刷新数据失败');
	} finally {
		state.refreshLoading = false;
	}
};

// 数据导出
// const handleExport = async () => {
// 	try {
// 		state.exportLoading = true;

// 		// 准备导出参数
// 		const params = {
// 			workTime: state.queryParams.workTime,
// 			className: state.queryParams.className,
// 			workAreaId: state.queryParams.workAreaId,
// 			keyword: state.queryParams.keyword,
// 		};

// 		// 调用导出接口
// 		const res = await planViewApi.exportData(params);

// 		// 处理文件下载
// 		if (res && res.data) {
// 			const blob = new Blob([res.data], {
// 				type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
// 			});
// 			const url = window.URL.createObjectURL(blob);
// 			const link = document.createElement('a');
// 			link.href = url;
// 			link.download = `计划视图数据_${state.queryParams.workTime || '全部'}.xlsx`;
// 			document.body.appendChild(link);
// 			link.click();
// 			document.body.removeChild(link);
// 			window.URL.revokeObjectURL(url);

// 			ElMessage.success('数据导出成功');
// 		}
// 	} catch (error) {
// 		console.error('导出数据失败:', error);
// 		ElMessage.error('导出数据失败');
// 	} finally {
// 		state.exportLoading = false;
// 	}
// };

// 清除缓存
// const handleClearCache = async () => {
// 	try {
// 		// 调用清除缓存接口
// 		await planViewApi.clearPlanViewCache({
// 			workTime: state.queryParams.workTime,
// 			className: state.queryParams.className,
// 			workAreaId: state.queryParams.workAreaId,
// 		});

// 		// 清空本地缓存
// 		state.areaChartDataCache = {};
// 		state.categoryChartDataCache = {};

// 		ElMessage.success('缓存清除成功');
// 	} catch (error) {
// 		console.error('清除缓存失败:', error);
// 		ElMessage.error('清除缓存失败');
// 	}
// };

// 重试获取统计数据
const handleRetry = async () => {
	try {
		state.dataError = false; // 重置错误状态
		// 重新尝试获取数据
		const queryParams = {
			workTime: state.queryParams.workTime,
			className: state.queryParams.className,
			workAreaId: state.queryParams.workAreaId,
		};
		await store.refreshAllData(queryParams);
	} catch (error) {
		state.dataError = true; // 设置错误状态
		console.error('重试获取数据失败:', error);
	}
};

// 推送延期通知
const handleSendNotifications = async (event?: Event) => {
	if (event) {
		event.preventDefault();
		event.stopPropagation();
	}

	// 权限检查
	if (!auth('planview:sendNotification')) {
		ElMessage.error('您没有推送通知的权限');
		return;
	}

	console.log('推送通知按钮被点击');
	try {
		console.log('开始初始化通知配置...');

		// 初始化选项（如果尚未加载）
		if (state.notificationConfigDialog.userOptions.length === 0) {
			console.log('初始化用户选项...');
			await initUserOptions();
		}
		if (state.notificationConfigDialog.roleOptions.length === 0) {
			console.log('初始化角色选项...');
			await initRoleOptions();
		}

		console.log('初始化通知配置数据...');
		// 初始化通知配置数据
		state.notificationConfigDialog.formData = {
			workTime: state.queryParams.workTime,
			className: state.queryParams.className ?? undefined,
			workAreaId: state.queryParams.workAreaId ?? undefined,
			notificationType: 3, // 推送全部延期（开工+完工）
			delayLevels: [4], // 推送所有等级的延期
			recipientMode: 1, // 默认自动按权限配置
			specificUserIds: [],
			specificRoleIds: [],
			includeSubordinates: false,
			customMessage: '',
		};

		// 清空之前的预览
		state.notificationConfigDialog.preview = null;

		console.log('显示通知配置对话框...');
		// 显示通知配置对话框
		state.notificationConfigDialog.visible = true;

		console.log('通知配置对话框已显示');
		console.log('对话框状态:', state.notificationConfigDialog.visible);
	} catch (error) {
		console.error('打开通知配置对话框失败:', error);
		ElMessage.error('打开通知配置失败');
	}
};

// 初始化用户选项
const initUserOptions = async () => {
	try {
		const response = await sysUserApi.apiSysUserPagePost({
			page: 1,
			pageSize: 100,
			descStr: 'createTime',
		});
		if (response?.data?.result?.items) {
			state.notificationConfigDialog.userOptions = response.data.result.items.map((user: any) => ({
				value: user.id,
				label: user.name || user.realName || user.account,
				phone: user.phone,
			}));
		}
	} catch (error) {
		console.error('获取用户列表失败:', error);
	}
};

// 初始化角色选项
const initRoleOptions = async () => {
	try {
		const response = await sysRoleApi.apiSysRoleListGet();
		if (response?.data?.result) {
			state.notificationConfigDialog.roleOptions = response.data.result.map((role: any) => ({
				value: role.id,
				label: role.name,
				code: role.code,
			}));
		}
	} catch (error) {
		console.error('获取角色列表失败:', error);
	}
};

// 预览接收人
const handlePreviewRecipients = async () => {
	try {
		state.notificationConfigDialog.previewLoading = true;

		const response = await planDelayViewApi.previewNotificationRecipients(state.notificationConfigDialog.formData);
		if (response?.data?.result) {
			state.notificationConfigDialog.preview = response.data.result;
		} else {
			ElMessage.warning('预览失败，请检查配置参数');
		}
	} catch (error) {
		console.error('预览接收人失败:', error);
		ElMessage.error('预览失败，请稍后重试');
	} finally {
		state.notificationConfigDialog.previewLoading = false;
	}
};

// 确认发送通知
const handleConfirmSendNotification = async () => {
	try {
		state.notificationConfigDialog.loading = true;

		const response = await planDelayViewApi.sendDelayNotifications(state.notificationConfigDialog.formData);
		console.log('延期通知推送响应:', response);

		if (response?.data?.result?.success) {
			const result = response.data.result;
			ElMessage.success({
				message: `推送成功！共推送 ${result.totalDelayCount} 项延期给 ${result.notifiedUserCount} 位用户`,
				duration: 5000,
				showClose: true,
			});

			// 关闭对话框
			state.notificationConfigDialog.visible = false;

			// 显示推送详情
			if (result.details && result.details.length > 0) {
				const detailsHtml = result.details
					.map(
						(detail: any) =>
							`<div style="margin-bottom: 8px;">
						<strong>${detail.workAreaName}</strong>: ${detail.delayItemCount}项延期 
						(严重:${detail.severeDelayCount} 中等:${detail.mediumDelayCount} 轻微:${detail.lightDelayCount})
						→ 推送给 ${detail.notifiedUserNames.slice(0, 3).join(', ')}${detail.notifiedUserNames.length > 3 ? ` 等${detail.notifiedUserNames.length}人` : ''}
					</div>`
					)
					.join('');

				ElMessageBox.alert(detailsHtml, '推送详情', {
					dangerouslyUseHTMLString: true,
					confirmButtonText: '知道了',
				});
			}
		} else {
			ElMessage.warning(response?.data?.result?.errorMessage || '推送失败，请稍后重试');
		}
	} catch (error) {
		console.error('推送延期通知失败:', error);
		ElMessage.error('推送延期通知失败，请检查网络连接');
	} finally {
		state.notificationConfigDialog.loading = false;
	}
};

// 清除缓存
const handleClearCache = async () => {
	try {
		// 清空Store缓存
		store.clearAllData();
		
		// 清空本地延期缓存
		// 移除：延期图表数据缓存已迁移到Store管理
		// state.areaDelayChartDataCache = null;
		// state.categoryDelayChartDataCache = null;

		// 重新获取数据
		const queryParams = {
			workTime: state.queryParams.workTime,
			className: state.queryParams.className,
			workAreaId: state.queryParams.workAreaId,
		};
		await store.refreshAllData(queryParams);

		ElMessage.success('缓存清除成功');
	} catch (error) {
		console.error('清除缓存失败:', error);
		ElMessage.error('清除缓存失败');
	}
};

// 初始化SignalR延期通知监听
const initSignalRNotificationListener = () => {
	// 监听延期通知消息（持久化通知）
	signalR.on('PublicNotice', handleDelayNotificationMessage);
	// 保留原有的实时消息监听（兼容性）
	signalR.on('ReceiveMessage', handleDelayNotificationMessage);
	console.log('SignalR延期通知监听已初始化');
};

// 移除SignalR延期通知监听
const removeSignalRNotificationListener = () => {
	// 移除延期通知消息监听
	signalR.off('PublicNotice', handleDelayNotificationMessage);
	signalR.off('ReceiveMessage', handleDelayNotificationMessage);
	console.log('SignalR延期通知监听已移除');
};

// 处理接收到的延期通知消息
const handleDelayNotificationMessage = (message: any) => {
	console.log('收到SignalR延期通知消息:', message);

	// 兼容两种消息格式：PublicNotice (通知对象) 和 ReceiveMessage (消息对象)
	let title = '';
	let content = '';

	if (message.title && message.content) {
		// PublicNotice 格式：通知对象
		title = message.title;
		content = message.content;
	} else if (message.Title && message.Message) {
		// ReceiveMessage 格式：消息对象
		title = message.Title;
		content = message.Message;
	}

	// 通过消息标题或内容识别延期警报
	const isDelayAlert = title?.includes('延期警报') || title?.includes('延期') || (content?.includes('延期') && (content?.includes('严重') || content?.includes('中等') || content?.includes('轻微')));

	// 只处理延期警报类型的消息
	if (isDelayAlert) {
		ElNotification({
			title: title || '延期警报',
			message: content,
			type: 'warning',
			duration: 0, // 不自动关闭
			showClose: true,
			position: 'top-right',
			onClick: () => {
				// 点击通知时可以跳转到对应的延期详情
				console.log('点击了延期通知');
			},
		});

		// 如果当前在计划看板页面，可以刷新数据
		if (window.location.pathname.includes('planview')) {
			ElMessage({
				message: '收到新的延期警报，数据将自动刷新',
				type: 'info',
				duration: 3000,
			});

			// 延迟刷新数据，避免过于频繁
			setTimeout(() => {
				handleRefresh();
			}, 2000);
		}
	}
};
</script>

<style lang="scss" scoped>
.planView-container {
	width: 100%;
	padding: 4px;
	min-height: 100vh;
}

.art-custom-card {
	margin-bottom: 8px;
	border: 1px solid var(--el-border-color-light);
	border-radius: 4px;
	transition: all 0.3s ease;
	&:hover {
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	}
}

.plan-analysis-tabs {
	width: 100%;

	.el-card__header {
		background: var(--el-bg-color);
		color: var(--el-text-color-primary);
		border-bottom: 1px solid var(--el-border-color-light);
		padding: 15px 20px;
	}

	.card-header {
		font-size: 14px;
		font-weight: 500;
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.header-actions {
		margin-left: auto;
		z-index: 1000;
		position: relative;
	}

	.analysis-tabs {
		.el-tabs__content {
			padding: 20px;
		}

		.el-tabs__header {
			margin-bottom: 0;
		}

		.el-tabs__item {
			display: flex;
			align-items: center;
			gap: 4px;
			font-size: 14px;
			font-weight: 500;

			.filter-info {
				font-size: 11px;
				opacity: 0.8;
				font-weight: normal;
				margin-left: 4px;
			}
		}

		.el-tabs__item.is-active {
			color: var(--el-color-primary);
			font-weight: 600;
		}
	}

	// 月度看板tab内容样式
	.monthly-tab-content {
		.monthly-display-mode-selector {
			text-align: center;
			margin-bottom: 15px;
			padding-bottom: 10px;
			border-bottom: 1px solid var(--el-border-color-lighter);
		}
		
		.monthly-split-mode {
			.monthly-chart-item {
				height: 400px;
				margin-bottom: 20px;
				background: var(--el-bg-color);
				border-radius: 4px;
				border: 1px solid var(--el-border-color-light);
				box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
				
				&:last-child {
					margin-bottom: 0;
				}
			}
		}
		
		.monthly-combined-mode {
			height: 400px;
			background: var(--el-bg-color);
			border-radius: 4px;
			padding: 15px;
			border: 1px solid var(--el-border-color-light);
			box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		}
	}

	// 延期分析tab内容样式
	.delay-tab-content {
		.analysis-charts {
			padding: 0;

			.chart-section {
				margin-bottom: 30px;

				&:last-child {
					margin-bottom: 0;
				}

				.section-header {
					display: flex;
					align-items: center;
					gap: 8px;
					margin-bottom: 15px;
					font-size: 16px;
					font-weight: 600;
					color: var(--el-text-color-primary);

					.filter-info {
						font-size: 12px;
						opacity: 0.8;
						font-weight: normal;
						margin-left: 8px;
					}
				}

				.chart-container {
					height: 400px;
					border: 1px solid var(--el-border-color-light);
					border-radius: 4px;
					overflow: hidden;
				}
			}
		}
	}

	// 延期明细tab内容样式
	.delay-details-tab-content {
		padding: 0;
	}

	// 计划清单tab内容样式
	.plan-lists-tab-content {
		padding: 0;
	}

	// 更新信息分析tab内容样式
	.update-analysis-tab-content {
		padding: 0;
	}
}

:deep(.el-card) {
	border-radius: 4px !important;
}
:deep(.el-card__header) {
	border-radius: 4px 4px 0 0 !important;
}

// 响应式设计
@media (max-width: 768px) {
	.planView-container {
		padding: 4px;
	}
	.art-custom-card {
		margin-bottom: 8px;
	}

	.plan-analysis-tabs {
		.el-card__header {
			padding: 12px 15px;
		}

		.card-header {
			flex-direction: column;
			align-items: flex-start;
			gap: 5px;
		}

		.header-actions {
			width: 100%;
			display: flex;
			justify-content: flex-end;
		}

		.analysis-tabs {
			.el-tabs__content {
				padding: 10px;
			}

			.el-tabs__item {
				font-size: 12px;

				.filter-info {
					font-size: 10px;
				}
			}
		}

		// 移动端月度看板样式
		.monthly-tab-content {
			.monthly-display-mode-selector {
				margin-bottom: 10px;
				padding-bottom: 8px;
			}
			
			.monthly-split-mode {
				.monthly-chart-item {
					height: 300px;
					margin-bottom: 15px;
				}
			}
			
			.monthly-combined-mode {
				height: 300px;
				padding: 10px;
			}
		}

		// 移动端延期分析样式
		.delay-tab-content {
			.analysis-charts {
				.chart-section {
					margin-bottom: 20px;

					.section-header {
						font-size: 14px;
						margin-bottom: 10px;

						.filter-info {
							font-size: 11px;
						}
					}

					.chart-container {
						height: 300px;
					}
				}
			}
		}
	}
}
</style>
